package com.appkudos.view;

import com.appkudos.controller.RecController;
import com.appkudos.controller.UserController;
import com.appkudos.model.Group;
import com.appkudos.model.User;
import com.appkudos.model.App;
import com.appkudos.view.R;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SimpleAdapter.ViewBinder;

public class UserAppsActivity extends Activity implements ViewBinder, OnClickListener, Runnable{
    // list view for displaying the installed apps
	private ListView lv;
	private List<App> list;
	ArrayList<App> newapps ;
	private PackageManager pm;
	private TextView title_tv;
	private Activity PARENTACTIVITY;
	UserController uc;
	User user;
	User friend;
	App app;
	List<App> prev_apps;
	int icontry;
	
	// widgets from app
	String appName;
	String appDesc;
	String appId;
	//User friend;
	ArrayList<Group> groups;
	Button recBtn;
	
	// widgets for write review
	Bundle extras;
	Spinner recToFriendSpinner;
	Spinner recToGroupSpinner;
	TextView appText;
	EditText commentEditText;
	Button postReviewBtn;
	RecController rc =  new RecController();
	Group curGroup;
	Group group;
	String display_option;
	List<Group> user_groups;
	
    ProgressDialog pd;
     
    int numApps;
    int prevApps;
    int newApps;
    int brandNew;
     
     
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PARENTACTIVITY = this;
        
        // get data from bundle
        Intent launchIntent = getIntent();
        Bundle extras = launchIntent.getExtras();
        uc = new UserController();
        user = uc.getCurrentUser(extras);
        friend = uc.getFriend(extras);
        display_option = extras.getString("display_opt");
        curGroup = uc.getCurrentGroup(extras);
        

   	 if(display_option!= null){
	        if(display_option.equals(this.getString(R.string.select_app))){ // display select app
	     	   displaySelectApp();
	        }
	        else if (display_option.compareTo("view_app") == 0){
	        		displayAppActivity(extras.getString("appname"), extras.getString("appdesc"), extras.getString("appid"));
	        	
	        }else if (display_option.compareTo("create_rec") == 0){
	        		displayWriteReviewActivity(extras.getString("appname"), extras.getString("appdesc"), extras.getString("appid"));
	        	
	        }
        }else{
        	// display user apps activity
            setContentView(R.layout.view_title_list);       
            // set the title of the page 
            title_tv=(TextView)findViewById(R.id.tl_title);
            // get list view from layout
            lv=(ListView)findViewById(R.id.tl_list);
            
            // check whether to display user or friend profile
            if(friend != null && friend.getUsername().compareTo(user.getUsername())!=0){
            	title_tv.setText(friend.getFirstname()+" "+friend.getLastname()+"'s Installed App List");
            	initInstalledApps(friend);
            }else{// display user profile
            	if(friend != null && friend.getUsername().compareTo(user.getUsername())==0){
            		friend = null;
            	}
            	title_tv.setText(user.getFirstname()+" "+user.getLastname()+"'s Installed App List");
                // Show loading dialog while apps are installed/saved
                pd = ProgressDialog.show(this, "", "Loading Apps. Please wait...", true);
            }
            
            Thread thread = new Thread(this);
            thread.start();
       }   
   	 
    	
   }
    
    /***
     * Saves/installs all user apps in the background
     * Called when the thread starts
     * Note: Cannot alter View elements in the background
     */
    public void run() {
        displayUserAppsActivity();
        handler.sendEmptyMessage(0);
    }
    
    /***
     *  Gets called when the thread is finished running
     *  Closes progress dialog and updates View elements
     */
    private Handler handler = new Handler() {
    	@Override
        public void handleMessage(Message msg) {
    		if(pd != null && pd.isShowing()){
                pd.dismiss();
    		}
    	    initInstalledApps(user);
    	}
    };
    
    
    /**
     * Display user apps activity
     */
    private void displayUserAppsActivity(){
            	
        // check whether to display user or friend profile
        if(friend != null && friend.getUsername().compareTo(user.getUsername())!=0){
        	//title_tv.setText(friend.getFirstname()+" "+friend.getLastname()+"'s Installed App List");
        	//initInstalledApps(friend);
        }else{// display user profile
        	if(friend != null && friend.getUsername().compareTo(user.getUsername())==0){
        		friend = null;
        	}
        	//title_tv.setText(user.getFirstname()+" "+user.getLastname()+"'s Installed App List");
        
	        // get installed apps from the device
	        pm = this.getPackageManager();
	        Intent intent = new Intent(Intent.ACTION_MAIN, null);
	        intent.addCategory(Intent.CATEGORY_LAUNCHER);
	        List apps = pm.queryIntentActivities(intent, PackageManager.PERMISSION_GRANTED);  
	        Iterator i = apps.iterator();
			
		    // save installed apps in db and populate the list view to display the installed apps
	        list = extractInstalledApps(pm, i);
	        saveInstalledApps();
		}
		
		
    }
    
    /**
     * saved the list of installed apps to database (UserAppsActivity)
     * @param pm - package manager
     * @param i - iterator
     */
    private List extractInstalledApps(PackageManager pm, Iterator i) {
    	// initialize variable 
    	ResolveInfo rInfo; 
    	list = new ArrayList<App>();
    	

    	// get all previously installed fav apps
    	prev_apps = uc.getAppsForUser(user.getUsername());

        while (i.hasNext()) {
//    		counter++;
    		rInfo = (ResolveInfo) i.next(); 
    		// extract data for each app
    		String appid = Integer.toString(rInfo.activityInfo.applicationInfo.uid);
        	String appName = rInfo.activityInfo.applicationInfo.loadLabel(pm).toString();
        	Drawable icon = rInfo.activityInfo.applicationInfo.loadIcon(pm);
        	String appDesc = (String) rInfo.activityInfo.applicationInfo.loadDescription(pm);
        	icontry = rInfo.activityInfo.applicationInfo.icon;
        	boolean isFav = false;
        	if(appDesc == null){ 
        		appDesc = "No description available";
        	}
        	boolean isInstalled = true;
        	String dateInstalled = "";
        	
        	// create app object and add to list
        	app = new App(appid, appName, appDesc, dateInstalled, isFav, isInstalled, icon);
    	    list.add(app);
        	
        }    
    	
    	// sort the list of apps by title
    	Collections.sort(list);
 
    	return list;
    }
    
    
    /**
     * saved the list of installed apps to database (UserAppsActivity)
     * @param pm - package manager
     * @param i - iterator
     */
    private List saveInstalledApps() {   
//    	for(int j=0; j<prev_apps.size();j++){
//    		uc.removeApp(user.getUsername(), prev_apps.get(j).getAppid());
//        	}
    	int counter;
    	newapps = new ArrayList<App>();
    	int loc;
    	counter = 0;
    	while(counter<list.size()){
    		
    		if(prev_apps.size() == 0){
    			newapps.add(list.get(counter));
    		}
    		else{
		    	loc = findMatchingApp(prev_apps,list.get(counter));
		 
			    if(loc > -1){
			    	prev_apps.remove(loc);
			    }else{
			    	if(list.get(counter).getAppid().compareTo("10000")!=0 && list.get(counter).getAppid().compareTo("10004")!=0){
			    		newapps.add(list.get(counter));
			    	}
			    }
	    	}
    		counter++;
    	}	
    	
    	// delete the uninstalled apps
    	if(prev_apps.size()>0){
    		for(int count=0; count < prev_apps.size(); count++){
    			uc.removeApp(user.getUsername(), prev_apps.get(count).getAppid());
    		}
    	}
    //	title_tv.setText("now: "+list.size()+"prev: "+prev_apps.size()+"new:"+newapps.size());
    	
    	
    	List installed_list = uc.getAppsInDB();
    	int brandnew = 0;
    	// add the newly installed apps
    	if(newapps.size()>0){
    		App temp_app;
    		for(int count=0; count < newapps.size(); count++){
    			temp_app = newapps.get(count);
    			if(findMatchingApp(installed_list, temp_app) > -1){ // app is installed
    				uc.addApp(user.getUsername(), temp_app.getAppid(), temp_app.getAppName(),temp_app.getAppDesc());   
    			}else{ // app is not installed
    				uc.addNewApp(user.getUsername(), temp_app.getAppid(), temp_app.getAppName(),temp_app.getAppDesc());   
        			brandnew++;
    			}		
    		}
    	}	
    	numApps = list.size();
    	prevApps = prev_apps.size();
    	newApps = newapps.size();
    	brandNew = brandnew;
//   	 Toast.makeText(getApplicationContext(), list.size() +" num current",Toast.LENGTH_SHORT).show();   
    	return list;
    }
    
    private int findMatchingApp(List<App> origin, App app){
    	int found = -1;
    	int j=0; // counter
    	Iterator<App> iter = origin.iterator();
    	App temp;
    	while(iter.hasNext() && found == -1){
    		temp = iter.next();
    		if(temp.getAppName().compareTo(app.getAppName())==0 && temp.getAppid().compareTo(app.getAppid())==0){
    			found = j;
    		}else{
    			j++;
    		}	
    	}
    	return found;
    }
    /**
     * display the list of apps in list view (UserAppsActivity)
     * @param curUser
     */
    private void initInstalledApps(User curUser){
       
     //   title_tv.setText("Total Apps: "+numApps+"    Newly Installed: "+newApps);
    	
    	
    	Map<String, App> itemData;
    	List<Map<String, App>> listData = new ArrayList<Map<String, App>>();
    	
    	list = uc.getAppsForUser(curUser.getUsername());
    	Collections.sort(list);
    	
    	// put the apps into a hashmap (used for input by simple adapter)
    	for(int j=0; j<list.size();j++){
    		itemData = new HashMap<String, App>(1);
    		app = (App) list.get(j);
    		itemData.put("app_list_linearLayout1", app);
    		listData.add(itemData);
    	}   
    	
    	// bind simple adapter to the list view
        SimpleAdapter simpleAdapter = new SimpleAdapter(this, listData, R.layout.app_list,
                new String[] {
                    "app_list_linearLayout1"
                }, new int[] {
                    R.id.app_list_linearLayout1
                });
        
        // bind viewBinder to adapter and set adapter to listview
        simpleAdapter.setViewBinder(this);
        lv.setAdapter(simpleAdapter);
        
     // when item is clicked go to app page
	    lv.setOnItemClickListener(new OnItemClickListener() {
	           public void onItemClick(AdapterView<?> parent, View view,
	               int position, long id) {
	        	   
	        	   // When clicked, show a toast with the TextView text
	        	   App item = (App) list.get(position);
//	        	   
	            	Intent intent = new Intent(PARENTACTIVITY, AppKudos.class);
	                  intent = uc.passCurrentUser(intent, user);
	                  if(friend!=null){
	                	  intent = uc.passFriend(intent, friend);
	                  }
	                  intent.putExtra("tab", PARENTACTIVITY.getString(R.string.tab_user_app));
	                  intent.putExtra("display_opt", "view_app");
	                  intent = uc.passApp(intent, item);
	          		  startActivity(intent);
	          		  
//	        	   displayAppActivity(item.getAppName(), item.getAppDesc(), item.getAppid());
	           }
	    });        
	    
    }
        
    
    @Override
    public boolean setViewValue(View view, Object data, String stringRepresetation) {  
    	// bind the list for user apps activity
        if(view instanceof LinearLayout){ // display list for user app view
	    	// get data for the row
	    	App app = (App) data;
	        LinearLayout layout = (LinearLayout) view;
	        
	        // bind information to the textbox and icon
	        TextView tv1 = (TextView) layout.findViewById(R.id.app_text);
	        tv1.setText(app.getAppName());
	        if(app.getIcon() == null)
	        	tv1.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon,0,0,0);
	        else	
	        	tv1.setCompoundDrawablesWithIntrinsicBounds(app.getIcon(), null, null, null);
	        
	        // set the checkbox (checked if flagged as fav)
	        CheckBox box = (CheckBox) layout.findViewById(R.id.fav_check);
	        
	        if(friend != null){
	        	box.setVisibility(View.GONE);
	        }else{
		        // number the checkboxes
		        box.setTag(app.getAppid());
		        // check the box if app is marked as favourite
		        box.setChecked(app.isFav());
		        
		        // if checkbox is selected, then add as favourite app
		        // if checkbox is removed, then unmark as favourite
		        box.setOnClickListener(this);
	        }
        }else if(view instanceof TextView){ // display list for select app
        	// get data for the row
        	App app = (App) data;
        	TextView tv1 = (TextView) view;
            
            // bind information to the textbox and icon
//            TextView tv1 = (TextView) layout.findViewById(R.id.app_text);
            tv1.setText(app.getAppName());
        //    tv1.setCompoundDrawablesWithIntrinsicBounds(app.getIcon(), null, null, null);   
        }
        return true;
    }

    // onclick listener for checkboxes to mark an app as favourite
	@Override
	public void onClick(View v) {
    	CheckBox checkbox= (CheckBox) v;
        String appid = (String) checkbox.getTag();
    	
        if (checkbox.isChecked()) {
        	//TODO: uncomment add Fav app to db
        	 uc.addFavApp(user.getUsername(), appid);
        	
        	 Toast.makeText(getApplicationContext(), "Successfully marked as favourite app",Toast.LENGTH_SHORT).show();                	
                         	
        }else{
        	//TODO: uncomment remove Fav app to db
        	 uc.removeFavApp(user.getUsername(), appid);
        	 Toast.makeText(getApplicationContext(), "Successfully unmarked the app as favourite",Toast.LENGTH_SHORT).show();                	 
        }  
		
	}
	
	// display app activity view
	private void displayAppActivity(String app_name, String app_desc, String appid){
		 setContentView(R.layout.view_app);
		 this.appName = app_name;
		 this.appId = appid;
		 this.appDesc = app_desc;
		 
		 // init variables
		 TextView appNameText = (TextView) findViewById(R.id.app_app_name);
	        TextView appDescText = (TextView) findViewById(R.id.app_app_description);
	        recBtn = (Button) findViewById(R.id.app_recommend_btn);
 
	        this.appName = app_name;
//	        if(extras !=null)
//	        {
//	        	appName = extras.getString("app_name");
	        	appNameText.setText(appName);
	        	
//	        	appDesc = extras.getString("app_desc");
	        	appDescText.setText(appDesc);
	        	
//	        }
//	        	else{
//	        	appNameText.setText("N/A");
//	        	appDescText.setText("N/A");
//	        }
	        
	        
	        // only display "Recommend" button when the app has been installed
	        // check if app exists in installed apps list
	        List<com.appkudos.model.App> installedApps = uc.getAppsForUser(user.getUsername());
	        com.appkudos.model.App app;
	        boolean installed = true;
	        for(int i=0; i<installedApps.size();i++) {
	        	app = (com.appkudos.model.App) installedApps.get(i);
	        	// if app in list does not have same id as app clicked, don't display "Recommend" button
	        	if (app.getAppid() == appid) {
	        		installed = false;
	        		//Toast.makeText(getApplicationContext(), app.getAppid() + " " + extras.getString("app_id") ,Toast.LENGTH_SHORT).show();
	        	  	  
	        	}
	        }
	        
	        // hide "Recommend" button if the user hasn't installed the app or the displayed account is not the user's
	        if(friend != null || installed == false){
	        	recBtn.setVisibility(View.GONE);
	        }else{
		        recBtn.setOnClickListener(new OnClickListener() {
		            @Override
		            public void onClick(View v) {     
		            	// hook button to Write Review screen
	//	            	Intent intent = new Intent(PARENTACTIVITY, WriteReviewActivity.class);
	//	        	    intent = uc.passCurrentUser(intent, user);
	//	                intent.putExtra("app_name", appName);
	//	        	    startActivity(intent);
//		            	displayWriteReviewActivity(appName, appDesc, appId);
			        	   Intent intent = new Intent(PARENTACTIVITY, AppKudos.class);
			        	   intent = uc.passCurrentUser(intent, user);
			        	   if(friend != null){
			        		   intent = uc.passFriend(intent, friend);
			        	   }
			        	   intent.putExtra("tab", PARENTACTIVITY.getString(R.string.tab_user_app));
			               intent.putExtra("display_opt", "create_rec");
			        	   intent = uc.passApp(intent, new App(appId, appName, appDesc));
			          	   startActivity(intent);
		            }
		          }); 
	        }
	}
	
   // display write review activity
	private void displayWriteReviewActivity(String app_name, String app_desc, String app_id){
		 setContentView(R.layout.view_write_review);
		 
		 appName = app_name;
		 appDesc = app_desc;
		 appId = app_id;
		 
		   recToFriendSpinner = (Spinner) findViewById(R.id.wr_rec_to_friend_spinner);
	       recToGroupSpinner = (Spinner) findViewById(R.id.wr_rec_to_group_spinner);
	    	
	    	appText = (TextView) findViewById(R.id.app_text);
	    	
	    	// fill app name based on previous screen
//	    	if (extras!= null) {
	    		appText.setText(app_name);
//	    	}
	    	
	    	appText.setOnClickListener(new OnClickListener() {
	            @Override
	            public void onClick(View v) {     
	            	// hook button to Write Review screen
		        	   App item = new App(appId, appName, appDesc);
//		        	   
		            	Intent intent = new Intent(PARENTACTIVITY, AppKudos.class);
		                  intent = uc.passCurrentUser(intent, user);
		                  if(friend!=null){
		                	  intent = uc.passFriend(intent, friend);
		                	  
		          	    	
		                  }
		                  intent.putExtra("tab", PARENTACTIVITY.getString(R.string.tab_user_app));
		                  intent.putExtra("display_opt", "view_app");
		                  intent = uc.passApp(intent, item);
		          		  startActivity(intent);
	            	
//	            	 displayAppActivity(appName, appDesc, appId);
	        	    
	            }
	          });  
	    	commentEditText = (EditText) findViewById(R.id.wr_comment_edittext);
	    	
	    	postReviewBtn = (Button) findViewById(R.id.wr_post_review_btn);	    	
	    	postReviewBtn.setOnClickListener(new OnClickListener() {
	            @Override
	            public void onClick(View v) {     
	            	int friend = recToFriendSpinner.getSelectedItemPosition();
		    		int group = recToGroupSpinner.getSelectedItemPosition();
		    		String comment = commentEditText.getText().toString();
		    		
		    		if (friend == 0 && group == 0){
		    			Toast.makeText(getApplicationContext(), "No friend/group selected",Toast.LENGTH_SHORT).show();
		    		}else if(comment.compareTo("")==0){
		    			Toast.makeText(getApplicationContext(), "Please enter comment",Toast.LENGTH_SHORT).show();
		    		}else{
		    			if (friend != 0){
		    				String friendString = recToFriendSpinner.getItemAtPosition(friend).toString();
		    				rc.addRecommendation(user.getUsername(), comment, appId, 
		        					friendString, false);
		    			}
		    			
		    			if (group != 0){
//		    				String groupString = recToGroupSpinner.getItemAtPosition(group).toString();
		    				String groupString = user_groups.get(group-1).getGroupID();
//		    				Toast.makeText(getApplicationContext(), "gid: "+groupString+",gname: "+,Toast.LENGTH_LONG).show();
		    				rc.addRecommendation(user.getUsername(), comment, appId, 
		        					groupString, true);
		    			}
		    			
		    			Toast.makeText(getApplicationContext(), "Sent!",Toast.LENGTH_SHORT).show();
		    			
		    			Intent intent = new Intent(PARENTACTIVITY, com.appkudos.view.AppKudos.class);
		    			intent = uc.passCurrentUser(intent, user);
		    			if(curGroup != null){
			    			intent = uc.passCurrentGroup(intent, curGroup);
			    			Toast.makeText(getApplicationContext(), "got group in write review",Toast.LENGTH_SHORT).show();
			    			
		    			}
			        	startActivity(intent);
		    		}
		    		
		    		//showDialog( 0 );
		        
	            }
	          }); 
	        populateRecommendTo();
	}
	
   // populate the fields in write review activity	
   public void populateRecommendTo() {
	    	// TODO (The name of the app and username has to be set before!!!)
	    	//appText.setText("10");
	    	
	    	//Friends
	    	//UserController uc = new UserController();
	    	List<User> user_friends = uc.getFriendsOfUser(user.getUsername());
//    		Toast.makeText(getApplicationContext(), "spinner_num_friends:" + user_friends,Toast.LENGTH_SHORT).show();
	    	ArrayAdapter <CharSequence> adapter =
	    		  new ArrayAdapter <CharSequence> (this, android.R.layout.simple_spinner_item);
	    	adapter.add("Choose a Friend");
	    	adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    	for (int i=0; i<user_friends.size(); i++){
	    		adapter.add(user_friends.get(i).getUsername());
	    	}
	    	
	    	recToFriendSpinner.setAdapter(adapter); 		 
	    	
	    	//Groups
	    	user_groups = uc.getGroupsOfUser(user.getUsername());
	    	
	    	ArrayAdapter <CharSequence> adapter2 =
	    		  new ArrayAdapter <CharSequence> (this, android.R.layout.simple_spinner_item);
	    	adapter2.add("Choose a Group");
	    	adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    	for (int i=0; i<user_groups.size(); i++){
	    		adapter2.add(user_groups.get(i).getGroupName());
	    	}
	    	
	    	// if group has been selected for an app to be recommended to it, fill in group name in spinner
	    	if (group != null) {
	    		String groupName = group.getGroupName();
	    		Toast.makeText(getApplicationContext(), "Group " + groupName + " was selected",Toast.LENGTH_SHORT).show();
	    		// search for this group name in the spinner
	    		int spinnerPosition = adapter.getPosition(groupName);
	    		Toast.makeText(getApplicationContext(), "Group " + spinnerPosition + " was selected",Toast.LENGTH_SHORT).show();
	    		// set the spinner to display this group name
	    		recToGroupSpinner.setAdapter(adapter2);
	    		recToGroupSpinner.setSelection(spinnerPosition);
	    	}
	    	else {
	    		recToGroupSpinner.setAdapter(adapter2);
	    	}
	    }  
   
   private void displaySelectApp(){
   	// set content view to apps_view xml
       setContentView(R.layout.view_title_list);  
       
       // set the title of the page 
       title_tv=(TextView)findViewById(R.id.tl_title);
       title_tv.setText("Select an app to recommend:");
     
       // get list view from layout
       lv=(ListView)findViewById(R.id.tl_list);
       
	    // initialize the list
       initInstalledApps();
		
		// when item is clicked go to app page
	    lv.setOnItemClickListener(new OnItemClickListener() {
	           public void onItemClick(AdapterView<?> parent, View view,
	               int position, long id) {
	        	   
	        	   // When clicked, show a toast with the TextView text
	        	   App item = (App) list.get(position);
	        	   
//	        	   displayWriteReviewActivity(item.getAppName(), item.getAppDesc(), item.getAppid());
	        	   Intent intent = new Intent(PARENTACTIVITY, AppKudos.class);
	        	   intent = uc.passCurrentUser(intent, user);
	        	   if(friend != null){
	        		   intent = uc.passFriend(intent, friend);
	        	   }
	        	   intent.putExtra("tab", PARENTACTIVITY.getString(R.string.tab_user_app));
	               intent.putExtra("display_opt", "create_rec");
	        	   intent = uc.passApp(intent, item);
	          	   startActivity(intent);
	             
	           }
	    });
   }
   
   /**
    * populate the list in select app screen with installed apps
    * @param pm - package manager
    * @param i - iterator
    */
    private void initInstalledApps(){
   	Map<String, App> itemData;
   	List<Map<String, App>> listData = new ArrayList<Map<String, App>>();
   	
   	list = uc.getAppsForUser(user.getUsername());
   	
   	// put the apps into a hashmap (used for input by simple adapter)
   	for(int j=0; j<list.size();j++){
   		itemData = new HashMap<String, App>(1);
   		app = (App) list.get(j);
   		itemData.put("select_app_text", app);
   		listData.add(itemData);
   	}    

   	// bind simple adapter to the list view
       SimpleAdapter simpleAdapter = new SimpleAdapter(this, listData, R.layout.list_select_app,
               new String[] {
                   "select_app_text"
               }, new int[] {
                   R.id.select_app_text
               });
       
       // bind viewBinder to adapter and set adapter to listview
       simpleAdapter.setViewBinder(this);
       lv.setAdapter(simpleAdapter);
   }
}